package game.view.map
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.utils.Dictionary;
	
	import game.model.scene.vo.MapConfigVO;
	import game.model.scene.vo.MapGridConfigVO;
	import game.resource.ResourceLoadHelper;
	
	public class MapView extends Sprite
	{
		private var vo:MapConfigVO = null;
		
		public function MapView(data:MapConfigVO)
		{
			vo = data;
			
			inits();
		}
		
		private function inits():void
		{
			// temp show the grid contour
			var l:uint = vo.gridList.length;
			for (var i:uint=0; i<l; i++)
			{
				var grid:MapGridConfigVO = vo.gridList[i];
				if (!grid) continue;
				var contour:Shape = new Shape();
				contour.graphics.beginFill(0xffffff * Math.random());
				contour.graphics.drawRect(0, 0, grid.width, grid.height);
				contour.graphics.endFill();
				contour.x = grid.x;
				contour.y = grid.y;
				addChild(contour);
			}
		}
		
		private var _hasLoaded:Dictionary = new Dictionary(true);
		public function addGrid(grid:MapGridConfigVO):void
		{
			if (_hasLoaded[grid])
				return;
			
			_hasLoaded[grid] = true;
			ResourceLoadHelper.loadMapGrid(grid.img, 
				function (data:*):void{onLoadComplete(data, grid)}
			);
		}
		
		private function onLoadComplete(data:Bitmap, grid:MapGridConfigVO):void
		{
			var bmp:Bitmap = data;
			if (!bmp)
				return;
			
			bmp.x = grid.x;
			bmp.y = grid.y;
			
			var bmpMask:Shape = new Shape();
			bmpMask.graphics.beginFill(0);
			bmpMask.graphics.drawRect(grid.x, grid.y, grid.width, grid.height);
			bmpMask.graphics.endFill();
			bmp.mask = bmpMask;
			
			addChild(bmp);
		}
	}
}